<template>
  <div class="short-video-comment">
    <!-- 评论列表 - 类似手机聊天窗口 -->
    <div class="comment-list-section" v-if="comments.length > 0">
      <div class="comment-list">
        <div class="comment-item" v-for="comment in reversedComments" :key="comment.comment_id">
          <div class="comment-avatar">
            <el-avatar 
              :size="30" 
              :src="comment.author?.avatar"
            >
              {{ comment.author?.name?.charAt(0) }}
            </el-avatar>
          </div>
          <div class="comment-content-wrapper">
            <div class="comment-content">
              <div class="author-name">{{ comment.author?.name || '未知用户' }}</div>
              <div class="comment-text">{{ comment.content }}</div>
            </div>
            <div class="comment-time">{{ formatDate(comment.created_at || comment.createdAt) }}</div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="pagination.total_pages > 1">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :total="pagination.total"
          layout="prev, pager, next"
          @current-change="handlePageChange"
          small
        />
      </div>
    </div>
    
    <!-- 无评论提示 -->
    <div class="no-comments" v-else>
      <el-empty description="暂无评论，快来发表第一条评论吧！" :image-size="80" />
    </div>
    
    <!-- 评论输入区域 -->
    <div class="comment-input-section">
      <el-input
        v-model="commentContent"
        type="textarea"
        :rows="3"
        placeholder="请输入您的评论..."
        maxlength="500"
        show-word-limit
      />
      <div class="comment-actions">
        <el-button 
          type="primary" 
          @click="submitComment"
          :loading="submitting"
          :disabled="!commentContent.trim()"
        >
          发表评论
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  createShortVideoComment, 
  getShortVideoCommentList 
} from '@/api/modules/shortVideo'
import type { ShortVideo, ShortVideoComment } from '@/api/modules/shortVideo'

const props = defineProps<{
  video: ShortVideo
}>()

const emit = defineEmits<{
  (e: 'comment-change', commentCount: number): void
}>()

// 评论内容
const commentContent = ref('')

// 评论列表
const comments = ref<ShortVideoComment[]>([])

// 计算属性：反转评论列表，使最新评论显示在底部
const reversedComments = computed(() => {
  return [...comments.value].reverse()
})

// 分页信息
const pagination = ref({
  page: 1,
  limit: 10,
  total: 0,
  total_pages: 0
})

// 状态
const submitting = ref(false)
const loading = ref(false)

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 获取评论列表
const fetchComments = async () => {
  if (!props.video.video_id) return
  
  loading.value = true
  try {
    const response = await getShortVideoCommentList({
      video_id: props.video.video_id,
      page: pagination.value.page,
      limit: pagination.value.limit
    })
    
    comments.value = response.data?.list || []
    if (response.data?.pagination) {
      pagination.value = {
        ...pagination.value,
        ...response.data.pagination
      }
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 监听视频变化
watch(() => props.video, (newVal) => {
  if (newVal && newVal.video_id) {
    fetchComments()
  }
}, { immediate: true })

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.value.page = page
  fetchComments()
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  if (!props.video.video_id) {
    return
  }
  
  submitting.value = true
  try {
    const response = await createShortVideoComment({
      video_id: props.video.video_id,
      content: commentContent.value.trim()
    })
    
    if (response.data) {
      // 清空输入框
      commentContent.value = ''
      
      // 更新评论数
      emit('comment-change', (props.video.comment_count || 0) + 1)
      
      // 重新获取评论列表
      pagination.value.page = 1
      await fetchComments()
      
      ElMessage.success('评论发表成功')
    }
  } catch (error) {
    console.error('发表评论失败:', error)
  } finally {
    submitting.value = false
  }
}

// 组件挂载时获取评论
onMounted(() => {
  if (props.video.video_id) {
    fetchComments()
  }
})
</script>

<style scoped>
.short-video-comment {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.comment-list-section {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 16px;
}

.comment-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.comment-item {
  display: flex;
  gap: 10px;
}

.comment-avatar {
  flex-shrink: 0;
}

.comment-content-wrapper {
  flex: 1;
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 10px;
  position: relative;
}

.comment-content-wrapper::before {
  content: "";
  position: absolute;
  left: -10px;
  top: 10px;
  border-top: 5px solid transparent;
  border-bottom: 5px solid transparent;
  border-right: 10px solid #f5f5f5;
}

.author-name {
  font-weight: 500;
  margin-bottom: 5px;
  font-size: 14px;
}

.comment-text {
  line-height: 1.5;
  font-size: 14px;
}

.comment-time {
  margin-top: 5px;
  font-size: 12px;
  color: #999;
  text-align: right;
}

.comment-input-section {
  flex-shrink: 0;
}

.comment-actions {
  margin-top: 10px;
  text-align: right;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.no-comments {
  text-align: center;
  padding: 20px 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
</style>